package com.lagou.springbootjpathymeleaf.example.config;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.dbcp.BasicDataSource;

import org.apache.zookeeper.CreateMode;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;

public class InitListener implements ServletContextListener {

    private static final String CONNENT_ADDR = "127.0.0.1:2181";
    private static final String URL = "/db/url";
    private ZkClient zkClient;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        zkClient = new ZkClient(CONNENT_ADDR, 5000, 5000);
        System.out.println(">>> connect to zookeeper");
         zkClient.createEphemeral(URL,"mysql://127.0.0.1/lagoutest?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false");

//        zkClient.subscribeChildChanges("/db",(parentPath,currentChilds)->{
//            System.out.println(">>>servicePath is changed:" + parentPath);
//            BasicDataSource datasource = (BasicDataSource) RuntimeContext.getBean("dataSource");
//            datasource.setUrl(zkClient.getChildren(URL).get(0));
//
//        });
        zkClient.subscribeDataChanges(URL,new IZkDataListener() {
            @Override
            public void handleDataChange(String URL, Object o) throws Exception {
                System.out.println("变更的节点为:" + URL + ", 变更内容为:" + o);
                Object dataSource = RuntimeContext.getBean("dataSource");
//                dataSource.
//                datasource.setUrl((String) o);
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {


            }
        });

    }




//监听servicePath下的子文件是否发生变化




//        cache.getListenable().addListener(new NodeCacheListener() {
//            @Override
//            public void nodeChanged() throws Exception {
//                if (URL.equals(cache.getCurrentData().getPath())) {
//                    BasicDataSource datasource = (BasicDataSource) RuntimeContext.getBean("dataSource");
//                    datasource.setUrl(new String(cache.getCurrentData().getData()));
//                }
//            }
//        });

        


    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}


